package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.MyBookchapterBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.ljfiction.book.tools.ToastUtils;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MyBookChapterActivity extends BaseActivity {

    @BindView(R.id.mychapter_back)
    ImageView mychapterBack;
    @BindView(R.id.mybookchapter_recycle)
    RecyclerView mybookchapterRecycle;
    private BaseItemDraggableAdapter mAdpter;
    private String volumeId, bookId;
    private List<MyBookchapterBean.DataBean> chapterlist = new ArrayList<>();
    private List<MyBookchapterBean.DataBean> chapterlistfirst = new ArrayList<>();
    private MyBookchapterBean myBookchapterBean;
    private int startNum = 0, endNum = 0, startChapterid = 0;
    private Intent intent;
    private String volumeName;
    private NoBackgLodDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_book_chapter);
        ButterKnife.bind(this);
        volumeId = getIntent().getStringExtra("volumeId");
        bookId = getIntent().getStringExtra("bookId");
        volumeName = getIntent().getStringExtra("volumeName");
        intView();
        intData();
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/books-authorChapterList/" + volumeId + "/1")

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (dialog==null){
                            dialog=new NoBackgLodDialog(MyBookChapterActivity.this,true);
                        }
                        dialog.show();
                    }
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dialog.dismis();
                        Gson gson = new Gson();
                        try {
                            myBookchapterBean = gson.fromJson(s, MyBookchapterBean.class);
                            if (myBookchapterBean.getReturnCode() == 200) {
                                chapterlistfirst.clear();
                                chapterlistfirst.addAll(myBookchapterBean.getData());
                                chapterlist.addAll(myBookchapterBean.getData());
                                if (chapterlist.size() == 0) {
                                    showToast("暂无章节内容，快去创建吧");
                                    goBack();
                                } else {
                                    mAdpter.notifyDataSetChanged();
                                }
                            } else {
                                if (myBookchapterBean.getReturnCode() == 400){
                                    showToast(myBookchapterBean.getMsg());
                                }
                                showToast(myBookchapterBean.getMsg());
                                goBack();
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intView() {
        mybookchapterRecycle.setAdapter(mAdpter = new BaseItemDraggableAdapter<MyBookchapterBean.DataBean, BaseViewHolder>(R.layout.mychapteritem, chapterlist) {
            @Override
            protected void convert(BaseViewHolder helper, MyBookchapterBean.DataBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.chaptername_mychapter, item.getChapterTitle())
                        .setText(R.id.time_mychapter, TimeTool.getTimeByLong(item.getReleaseTime()))
                        .setText(R.id.num_mychapter, "共" + String.valueOf(item.getChapterLength()) + "字");
                if (item.getChapterIsvip()==1){
                    helper.getView(R.id.isvip_mychapteritem).setVisibility(View.VISIBLE);
                }else {
                    helper.getView(R.id.isvip_mychapteritem).setVisibility(View.GONE);
                }
                if (item.getChapterState()==0){
                    helper.setText(R.id.isornoexamine,"已审核");
                }else {
                    helper.setText(R.id.isornoexamine,"未审核");
                }
            }
        });
        mybookchapterRecycle.setLayoutManager(new LinearLayoutManager(this));
        mybookchapterRecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mAdpter.setOnItemClickListener((adapter, view, position) -> {
            if (!UserManageBean.isLogin(MyBookChapterActivity.this)){
                return;
            }
            intent = new Intent(MyBookChapterActivity.this, MyBookChapterBianjiActivity.class);
           intent.putExtra("bookId",bookId);
           intent.putExtra("volumeId",volumeId);
           intent.putExtra("chapterId",String.valueOf(chapterlist.get(position).getId()));
           intent.putExtra("volumeName",volumeName);

            startActivity(intent);
        });
        ItemDragAndSwipeCallback itemDragAndSwipeCallback
                = new ItemDragAndSwipeCallback(mAdpter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(mybookchapterRecycle);

        // 开启拖拽
        mAdpter.enableDragItem(itemTouchHelper, R.id.ll_mychapter, true);
        mAdpter.setOnItemDragListener(onItemDragListener);

    }

    @OnClick(R.id.mychapter_back)
    public void onViewClicked() {
        goBack();
    }

    OnItemDragListener onItemDragListener = new OnItemDragListener() {
        @Override
        public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
            startNum = chapterlistfirst.get(pos).getChapterOrder();
            startChapterid = chapterlistfirst.get(pos).getId();
        }

        @Override
        public void onItemDragMoving(RecyclerView.ViewHolder source, int from,
                                     RecyclerView.ViewHolder target, int to) {
        }

        @Override
        public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
            endNum = chapterlistfirst.get(pos).getChapterOrder();
            toMovechapter();
        }
    };

    private void toMovechapter() {
        OkHttpUtils.post(HttpManager.IP + "/sys-chapteOrderUpdate")

                .params("startNum", String.valueOf(startNum))
                .params("endNum", String.valueOf(endNum))
                .params("bookid", bookId)
                .params("volumeid", volumeId)
                .params("startChapterid", String.valueOf(startChapterid))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                            chapterlist.clear();
                            intData();

                    }
                });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        chapterlist.clear();
        intData();
    }

}
